package api.flinkapi.apidemos;

import org.apache.flink.api.common.eventtime.SerializableTimestampAssigner;
import org.apache.flink.api.common.eventtime.WatermarkStrategy;
import org.apache.flink.api.common.functions.ReduceFunction;
import org.apache.flink.api.common.typeinfo.TypeHint;
import org.apache.flink.api.common.typeinfo.TypeInformation;
import org.apache.flink.api.java.tuple.Tuple3;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.windowing.assigners.SlidingEventTimeWindows;
import org.apache.flink.streaming.api.windowing.time.Time;
import org.apache.flink.streaming.api.windowing.windows.Window;

import java.time.Duration;

/***
 * @author hunter.d
 * @qq 657270652
 * @wx haitao-duan
 * @date 2021/7/22
 **/
public class WindowTest {
    public static void main(String[] args) throws Exception {

        StreamExecutionEnvironment env = StreamExecutionEnvironment.createLocalEnvironmentWithWebUI(new Configuration());
        env.setParallelism(1);
        DataStreamSource<String> ds = env.socketTextStream("hdp01", 5656);
        SingleOutputStreamOperator<Tuple3<String, String, Integer>> dsTuple = ds.map(s -> Tuple3.of(s.split(",")[0], s.split(",")[1], Integer.parseInt(s.split(",")[2])), TypeInformation.of(new TypeHint<Tuple3<String, String, Integer>>() {
        }));

        //dsTuple.print();

        SingleOutputStreamOperator<Tuple3<String, String, Integer>> andWatermarks = dsTuple.assignTimestampsAndWatermarks(WatermarkStrategy.<Tuple3<String, String, Integer>>forBoundedOutOfOrderness(Duration.ofMillis(2000)).withTimestampAssigner(new SerializableTimestampAssigner<Tuple3<String, String, Integer>>() {
            @Override
            public long extractTimestamp(Tuple3<String, String, Integer> t, long recordTimestamp) {
                return Long.parseLong(t.f0);
            }
        }));

        SingleOutputStreamOperator<Tuple3<String, String, Integer>> res = andWatermarks
                .keyBy(t -> t.f1)
                .window(SlidingEventTimeWindows.of(Time.milliseconds(5000), Time.milliseconds(2000)))
                .minBy(2);
                /*.reduce(new ReduceFunction<Tuple3<String, String, Integer>>() {
                    @Override
                    public Tuple3<String, String, Integer> reduce(Tuple3<String, String, Integer> value1, Tuple3<String, String, Integer> value2) throws Exception {
                        return Tuple3.of(value1.f0, value1.f1, value1.f2 + value2.f2);
                    }
                });*/

        res.print();

        env.execute();


    }
}
